# python
from flask import Blueprint, request, jsonify
from ..common.Result import response, response_failure
from ..models.category import Category
from .. import db

category_bp = Blueprint('category_bp', __name__)


@category_bp.route('/category', methods=['POST'])
def create_category():
    data = request.get_json()
    parent_id = data.get('parent_id')
    if parent_id is None or parent_id == '':
        data['parent_id'] = 0
    category = Category(**data)
    db.session.add(category)
    db.session.commit()
    return response(data=category.to_dict(), msg="分类创建成功！")


@category_bp.route('/category/<int:id>', methods=['GET'])
def get_category(id):
    category = Category.query.get(id)
    if category is None:
        return response_failure(msg="没有这个分类")
    return response(data=category.to_dict())


@category_bp.route('/category/<int:id>', methods=['PUT'])
def update_category(id):
    data = request.get_json()
    category = Category.query.get_or_404(id)
    for key, value in data.items():
        if hasattr(category, key):
            setattr(category, key, value)
    db.session.commit()
    return response(msg='分类信息更新成功！')


@category_bp.route('/category/<int:id>', methods=['DELETE'])
def delete_category(id):
    category = Category.query.get_or_404(id)
    db.session.delete(category)
    db.session.commit()
    return response(msg='分类信息删除成功！')


@category_bp.route('/category/sub', methods=['GET'])
def get_subcategories():
    parent_id = request.args.get('parent_id', type=int)
    if parent_id is None:
        return response_failure(msg="没有提供父类别id")
    subcategories = Category.query.filter_by(parent_id=parent_id).all()
    subcategories_list = [subcategory.to_dict() for subcategory in subcategories]
    return response(data=subcategories_list)


@category_bp.route('/category/list', methods=['POST'])
def get_categories():
    data = request.get_json()
    page = data.get('page', 1)
    per_page = data.get('per_page', 10)
    categoryname = data.get('name', '')
    parent_id = data.get('parent_id', None)

    query = Category.query
    if categoryname:
        query = query.filter(Category.name.like(f'%{categoryname}%'))

    if parent_id is not None:
        query = query.filter(Category.parent_id == parent_id)

    query.order_by(Category.parent_id)

    categories = query.paginate(page=page, per_page=per_page, error_out=False)
    categories_list = [category.to_dict() for category in categories.items]

    return response(data={
        'categories': categories_list,
        'total': categories.total,
        'pages': categories.pages,
        'current_page': categories.page
    })

# python
@category_bp.route('/category/batch_delete', methods=['DELETE'])
def batch_delete_categories():
    data = request.get_json()
    ids = data.get('ids', [])
    if not ids:
        return response_failure(msg="没有提供要删除的分类ID列表")

    categories = Category.query.filter(Category.id.in_(ids)).all()
    if not categories:
        return response_failure(msg="没有找到要删除的分类")

    for category in categories:
        db.session.delete(category)
    db.session.commit()

    return response(msg="批量删除分类成功")
